package cn.hh.org.controller;

import cn.hh.basic.util.AjaxResult;
import cn.hh.basic.util.PageList;
import cn.hh.org.domain.Department;
import cn.hh.org.domain.Employee;
import cn.hh.org.query.DeptQuery;
import cn.hh.org.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
public class DeptController {
    @Autowired
    private IDeptService deptService;
    /*编辑*/
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department){
        /*通过id判断是新增还是删除*/
        try {
            if (department.getId()==null){
                deptService.add(department);
            }else {
                deptService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            /*反馈操作失败，及具体错误*/
            AjaxResult ajaxResult = AjaxResult.me().setMessage("操作失败" + e.getMessage());
            return ajaxResult;
        }
    }
    /*删除*/
    @DeleteMapping("/{id}")
    public AjaxResult deleteById(@PathVariable("id")Long id){
        try {
            deptService.deleteById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            /*反馈操作失败，及具体错误*/
            AjaxResult ajaxResult = AjaxResult.me().setMessage("操作失败" + e.getMessage());
            return ajaxResult;
        }
    }
    /*批量删除*/
    @PatchMapping
    public AjaxResult deleteByIds(@RequestBody Long[] ids){
        try {
            deptService.deleteByIds(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            /*反馈操作失败，及具体错误*/
            AjaxResult ajaxResult = AjaxResult.me().setMessage("操作失败" + e.getMessage());
            return ajaxResult;
        }
    }
    /*查询所有*/
    @GetMapping
    public List<Department> loadAll(){
        return deptService.loadAll();
    }
    /*分页*/
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DeptQuery query){
        return deptService.queryPage(query);
    }
    /*上级部门*/
    @GetMapping("/deptTrees")// id是请求地址后面带的值
    public List<Department> deptTree(){

        return deptService.deptTree();
    }
    @PostMapping("/emp")
    public PageList<Employee> findById(@RequestBody DeptQuery query){
        return deptService.findEmpById(query);
    }
}
